﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;

namespace Common.Compression
{
    public static class GZipHelper
    {
        /// <summary>
        /// Compresses data using GZip format
        /// </summary>
        /// <param name="RawData">A byte array that you want to be compressed.</param>
        /// <returns>Compressed bytes</returns>
        public static byte[] Compress(byte[] RawData)
        {
            if (RawData.isNull() || RawData.Length < 1)
                throw new ArgumentNullException("RawData");

            using (MemoryStream ms = new MemoryStream())
            {
                using (GZipStream gzs = new GZipStream(ms, CompressionMode.Compress))
                {
                    gzs.Write(RawData, 0, RawData.Length);
                }

                return ms.ToArray();
            }
        }

        /// <summary>
        /// Decompresses GZip data to original data.
        /// </summary>
        /// <param name="RawData">Compress GZip data</param>
        /// <returns>Original uncompressed data</returns>
        public static byte[] Decompress(byte[] RawData)
        {
            if (RawData.isNull() || RawData.Length < 1)
                throw new ArgumentNullException("RawData");

            using (MemoryStream dcmpData = new MemoryStream())
            {
                using (MemoryStream ms = new MemoryStream(RawData))
                {
                    using (GZipStream gzs = new GZipStream(ms, CompressionMode.Decompress))
                    {
                        gzs.CopyTo(dcmpData);
                    }
                }

                return dcmpData.ToArray();
            }
        }
    }
}
